package cn.com.haopy.yue.ai.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 向指定 URL 发送POST方法的请求
 *
 * @return 远程资源的响应结果
 */
@Slf4j
public class HttpUtils {

    // 超时配置（单位：毫秒）
    private static final int CONNECT_TIMEOUT = 30000;
    private static final int SOCKET_TIMEOUT = 30000;

    // 创建可配置的HttpClient实例
    private static final CloseableHttpClient httpClient = HttpClients.custom()
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectTimeout(CONNECT_TIMEOUT)
                    .setSocketTimeout(SOCKET_TIMEOUT)
                    .build())
            .build();

    /**
     * 执行GET请求
     *
     * @param url     请求地址
     * @param params  查询参数
     * @param headers 请求头
     * @return 响应内容字符串
     * @throws IOException        网络异常
     * @throws URISyntaxException URL格式异常
     */
    public static String get(String url,
                             Map<String, String> params,
                             Map<String, String> headers) throws IOException, URISyntaxException {
        log.info(url);
        if (Objects.nonNull(params)) {
            log.info(params.toString());
        }
        if (Objects.nonNull(headers)) {
            //log.info(headers.toString());
        }

        HttpGet httpGet = buildHttpGet(url, params, headers);
        return executeRequest(httpGet);
    }

    // 构造HttpGet对象
    private static HttpGet buildHttpGet(String url,
                                        Map<String, String> params,
                                        Map<String, String> headers) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);

        // 添加查询参数
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> parameters = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            uriBuilder.addParameters(parameters);
        }

        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 添加请求头
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }

        return httpGet;
    }

    // 执行请求并处理响应
    private static String executeRequest(HttpGet httpGet) throws IOException {
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new RuntimeException("HTTP请求失败，状态码: " + statusCode);
            }

            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity) : null;
        }
    }

    public static JSONObject doGetJson(String url, Map<String, String> params, Map<String, String> header) throws Exception {
        String result = get(url, header, params);
        if (!StringUtils.hasText(result)) {
            throw new Exception("访问错误！");
        }
        return JSON.parseObject(result);
    }


    /**
     * 向指定URL发送POST方法请求
     *
     * @param url    发送请求的URL
     * @param params
     * @return
     */
    public static JSONObject postJSON(String url, Map<String, String> header, Map<String, Object> params) {
        log.debug("访问地址：" + url);
        log.debug("header：" + JSONObject.toJSONString(header));
        log.debug("params:" + JSONObject.toJSONString(params));

        return postData(url, header, params, "json");
    }

    public static JSONObject postFormData(String url, Map<String, String> header, Map<String, Object> params) {
        log.debug("header：" + JSONObject.toJSONString(header));
        //log.debug("params:" + JSONObject.toJSONString(params));
        return postData(url, header, params, "form");
    }

    private static JSONObject postData(String url, Map<String, String> header, Map<String, Object> params, String postType) {
        try {
            String res = doPost(url, header, params, postType);

            System.out.println(res);

            if (res == null) {
                throw new Exception("访问异常");
            }

            return JSONObject.parseObject(res);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        return null;
    }

    private static String doPost(String url, Map<String, String> header, Map<String, Object> param, String postType)
            throws IOException, NoSuchAlgorithmException, KeyManagementException {
        System.out.println(url);
        CloseableHttpClient httpClient = getHttpClient(url.startsWith("https://"));

        CloseableHttpResponse response = null;
        String resultString = "";

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(300000)
                .setConnectTimeout(300000)
                .setConnectionRequestTimeout(300000)
                .build();


        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        if (header != null) {
            for (Map.Entry<String, String> e : header.entrySet()) {
                httpPost.setHeader(e.getKey(), e.getValue());
            }
        }

        HttpEntity entity = getHttpEntity(param, postType);

        if (entity != null) httpPost.setEntity(entity);

        //获取返回值
        CloseableHttpResponse res = httpClient.execute(httpPost);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            resultString = EntityUtils.toString(res.getEntity());// 返回json格式：
            log.info(url + " POST请求返回的数据是：" + resultString);
        }

        if (response != null) {
            response.close();
        }

        if (httpClient != null) {
            httpClient.close();
        }

        return resultString;
    }

    private static CloseableHttpClient getHttpClient(boolean isSSL) throws NoSuchAlgorithmException, KeyManagementException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        if (isSSL) {
            // SSL访问
            SSLContext context = SSLContext.getInstance("SSL");

            X509TrustManager manager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    // TODO Auto-generated method stub
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    // TODO Auto-generated method stub

                }
            };

            context.init(null, new TrustManager[]{manager}, null);

            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context,
                    NoopHostnameVerifier.INSTANCE);

            httpClient = HttpClients.custom().setSSLContext(context).build();
        }

        return httpClient;
    }

    private static HttpEntity getHttpEntity(Map<String, Object> params, String postType) throws UnsupportedEncodingException {
        if (params == null) return null;

        if ("form".equals(postType)) {
            List<NameValuePair> paramList = new ArrayList<>();
            for (String key : params.keySet()) {
                paramList.add(new BasicNameValuePair(key, params.get(key).toString()));
            }

            // 模拟表单
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");

            return entity;
        }

        if ("json".equals(postType)) {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(params), "utf-8");
            entity.setContentType("application/json; charset=utf-8");
            //entity.setContentEncoding("utf-8");

            return entity;
        }

        return null;
    }
}
